﻿using System;
using System.IO;
using System.Windows.Forms;

namespace FileExplorer.view
{
	public partial class RenameForm : Form
	{
		public RenameForm()
		{
			InitializeComponent();
		}

		private void btn_ChangeName_Click(object sender, EventArgs e)
		{
			bool bResult = false;

			if( tb_CurDir.Text != string.Empty 
				&& tb_OldName.Text != string.Empty 
				&& tb_NewName.Text != string.Empty)
			{
				/*
				 * rename 
				 */
				bResult = RenameFileInDirectory(tb_CurDir.Text);
			}

			if( bResult)
			{
				// list files
				string[] filePaths = Directory.GetFiles(tb_CurDir.Text);
				if (filePaths.Length > 0)
				{
					foreach (string item in filePaths)
					{
						rtb_Result.AppendText(item.Substring(item.LastIndexOf('\\') + 1, item.Length - item.LastIndexOf('\\') - 1) + "\n");
					}
				}

				MessageBox.Show("Success");
			}
			else
			{
				MessageBox.Show("Fail");
			}
		}

		private bool RenameFileInDirectory(string folderPath)
		{
			bool bResult = false;
			string sTemp = string.Empty;
			rtb_Result.Text = string.Empty;

			if (Directory.Exists(folderPath))
			{
				Directory.SetCurrentDirectory(folderPath);

				DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
				FileInfo[] fileInfo = dirInfo.GetFiles();

				foreach( FileInfo fI in fileInfo)
				{
					if( fI.Name.Contains(tb_OldName.Text))
					{
						sTemp = fI.Name.Replace(tb_OldName.Text, tb_NewName.Text);
						File.Move(fI.Name, sTemp);
					}
				}

				bResult = true;
			}
			else
			{
				rtb_Result.Text = "Not right path";
			}

			return bResult;
		}

		private void btn_Browser_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog folderDlg = new FolderBrowserDialog();
			folderDlg.ShowNewFolderButton = false;

			DialogResult dlgResult = folderDlg.ShowDialog();

			if( DialogResult.OK == dlgResult)
			{
				tb_CurDir.Text = folderDlg.SelectedPath;
			}
		}
	}
}
